package com.etoak.fliter;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.jwt.MyJwtUtil;
import com.etoak.properties.WhiteListProperties;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
public class TokenFliter implements GlobalFilter {

    @Autowired
    WhiteListProperties whiteListProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        /* 放行白名单 */
        String uri = request.getPath().value();
        if (whiteListProperties.getUrlList().contains(uri)){
            return chain.filter(exchange);
        }
        /* 获取请求头信息: Authorization  */
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token)){
            return noAuth(response,"请传入令牌!");
        }
        try{
            MyJwtUtil.parse(token);
        } catch (ExpiredJwtException e) {
           return noAuth(response,"令牌已过期");
        } catch (Exception e) {
            return noAuth(response,"令牌错误");
        }
        return chain.filter(exchange);
    }

    private Mono<Void> noAuth(ServerHttpResponse response, String message) {
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        ResultVO<Object> resultVO = ResultVO.failed(403, message);
        String jsonStr = JSONUtil.toJsonStr(resultVO);
        DataBuffer wrap = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Mono.just(wrap));
    }
}
